import { captchaFetch } from '@/services/login';
import { Button, message } from 'antd';
import React, {
  FC,
  useCallback,
  useEffect,
  useState
} from 'react';

import {v1} from 'uuid'

interface CaptchaImgProps {
  refresh?: boolean,
  getRandomKey?: (key?: string) => void
}

const CaptchaImg:FC<CaptchaImgProps> = ({ refresh,getRandomKey }) => {
  const [src, setSrc] = useState('');

  const fetchData = useCallback(() => {
    const randomKey = v1();
    captchaFetch({
      randomKey
    })
        .then((res) => {
          const { data } = res;
          setSrc(data);
          getRandomKey?.(randomKey)
        })
        .catch(() => {
          setSrc('');
          message.error('请重新点击获取验证码');
        });
  }, [getRandomKey]);

  const handleClick = () => {
    fetchData();
  };

  useEffect(() => {
    fetchData();
  }, [fetchData, refresh]);

  return (
      <Button type="link" onClick={handleClick} style={{ padding: 0 }}>
        <img src={src} alt="验证码" />
      </Button>
  );
};

export default CaptchaImg;
